<script setup lang="ts">
import { ref, watch } from 'vue'
import AppSelect from '~/components/AppSelect.vue'

interface Props {
  name: string
  type?: 'text' | 'password' | 'number' | 'email' | 'tel'
  modelValue?: string | number
  placeholder?: string
  required?: boolean
  disabled?: boolean
  isPhone?: boolean
  countryCode?: string
  validateResult?: {
    isValid: boolean;
    message: string;
  }
}

const props = withDefaults(defineProps<Props>(), {
  type: 'text',
  disabled: false,
  isPhone: false,
  countryCode: '+63'
})

const emit = defineEmits(['update:modelValue', 'focus', 'blur', 'change', 'update:validateResult'])

const inputValue = ref(props.modelValue || '')
const isFocused = ref(false)
const inputRef = ref<HTMLInputElement | null>(null)
const selectedCountryCode = ref(props.countryCode)

// 验证结果
const validationResult = ref({
  isValid: true,
  message: ''
})

// 国家代码选项
const { areaCodeOptionsFiltered } = useAreaCode()
const countryCodeOptions = ref([
  { label: '+63', value: '+63' },
  { label: '+86', value: '+86' },
  { label: '+1', value: '+1' },
  { label: '+44', value: '+44' },
  { label: '+81', value: '+81' },
  { label: '+82', value: '+82' }
])
onMounted(()=>{
  countryCodeOptions.value = areaCodeOptionsFiltered.value
})
// 监听外部model-value变化
watch(
  () => props.modelValue,
  (newVal) => {
    if (newVal !== undefined && newVal !== inputValue.value) {
      inputValue.value = newVal
      validateInput()
    }
  }
)

// 监听内部value变化向外发射事件
watch(inputValue, (val) => {
  emit('update:modelValue', val)
  validateInput()
})

// 监听验证结果变化并向外发射事件
watch(validationResult, (val: { isValid: boolean; message: string }) => {
  emit('update:validateResult', val)
})

// 验证输入内容
const validateInput = () => {
  const value = inputValue.value?.toString() || ''

  // 如果值为空且不是必填，则视为有效
  if (!value && !props.required) {
    validationResult.value = { isValid: true, message: '' }
    return
  }

  // 根据不同类型进行验证
  if (props.type === 'email') {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
    const isValid = emailRegex.test(value)
    validationResult.value = {
      isValid,
      message: isValid ? '' : '请输入有效的邮箱地址'
    }
  } else if (props.type === 'tel' || props.isPhone) {
    // 简单的手机号验证
    const phoneRegex = /^\d{6,15}$/
    const isValid = phoneRegex.test(value)
    validationResult.value = {
      isValid,
      message: isValid ? '' : '请输入有效的手机号码'
    }
  } else if (props.type === 'number') {
    const isValid = !isNaN(Number(value))
    validationResult.value = {
      isValid,
      message: isValid ? '' : '请输入有效的数字'
    }
  } else {
    // 文本类型验证
    const isValid = props.required ? value.length > 0 : true
    validationResult.value = {
      isValid,
      message: isValid ? '' : '此字段不能为空'
    }
  }
}

const handleInput = (e: Event) => {
  const target = e.target as HTMLInputElement
  inputValue.value = target.value
  emit('change', e)
  validateInput()
}

const handleFocus = (e: FocusEvent) => {
  isFocused.value = true
  emit('focus', e)
}

const handleBlur = (e: FocusEvent) => {
  isFocused.value = false
  emit('blur', e)
  // 失焦时再次验证
  validateInput()
}

const focus = () => {
  inputRef.value?.focus()
}

// 暴露给父组件的方法
defineExpose({
  focus,
  validate: validateInput
})
</script>

<template>
  <div class="app-input-wrapper" :class="{
    'is-focused': isFocused,
    'is-phone': isPhone,
    'is-disabled': disabled
  }">
    <!-- 手机号输入模式 -->
    <template v-if="isPhone">
      <div class="country-code-wrapper">
        <AppSelect v-model="selectedCountryCode" :options="countryCodeOptions" :showTrigger="true"
          class="country-code-select" />
      </div>
      <div class="divider"></div>
      <input ref="inputRef" :type="type" :name="name" :placeholder="placeholder" :value="inputValue"
        :required="required" :disabled="disabled" @input="handleInput" @focus="handleFocus" @blur="handleBlur"
        class="input-field phone-input">
    </template>

    <!-- 标准输入模式 -->
    <template v-else>
      <input ref="inputRef" :type="type" :name="name" :placeholder="placeholder" :value="inputValue"
        :required="required" :disabled="disabled" @input="handleInput" @focus="handleFocus" @blur="handleBlur"
        class="input-field">
    </template>

    <!-- 插槽用于添加额外的图标等 -->
    <slot name="suffix"></slot>
  </div>
</template>

<style lang="scss" scoped>
input[type="password"]::-ms-reveal,
input[type="password"]::-webkit-reveal-password-button,
input[type="password"]::-webkit-credentials-auto-fill-button {
  display: none !important;
  visibility: hidden !important;
  pointer-events: none !important;
}

.app-input-wrapper {
  display: flex;
  align-items: center;
  height: 42px;
  background: #292D2E;
  border: 1px solid var(---bg-black-53A4142, #3A4142);
  border-radius: 6px;
  overflow: hidden;
  transition: all 0.3s ease;

  &.is-focused {
    border: 1px solid var(---brand24EE89, #24EE89);
  }

  &.is-disabled {
    opacity: 0.6;
    cursor: not-allowed;
  }

  &.is-phone {
    .country-code-wrapper {
      min-width: 80px;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;

      .country-code-select {
        height: 100%;
        width: 100%;

        :deep(.select-trigger) {
          background: transparent;
          border-radius: 0;
          height: 100%;
          display: flex;
          align-items: center;
          padding: 10px 22px;
        }

        :deep(.arrow-icon) {
          width: 16px;
          height: 16px;
          background: transparent;
        }
      }
    }

    .divider {
      width: 1px;
      height: 20px;
      background-color: var(---bg-black-53A4142, #3A4142);
      margin: 0 2px;
    }

    .phone-input {
      padding-left: 8px;
    }
  }

  .input-field {
    flex: 1;
    height: 100%;
    padding: 0 12px;
    background: transparent;
    border: none;
    outline: none;
    color: #fff;
    font-size: 14px;

    &::placeholder {
      color: rgba(255, 255, 255, 0.5);
    }

    &:disabled {
      cursor: not-allowed;
    }
  }
}
</style>
